package vn.personal.anhht.bloback12.activity;

import java.util.ArrayList;

import vn.personal.anhht.bloback12.adapter.ContactsAdapter;
import vn.personal.anhht.bloback12.bean.ContactObject;
import vn.personal.anhht.bloback12.database.CallBlockDatabaseAdapter;
import vn.personal.anhht.bloback12.util.Constants;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;


public class TabPickContactActivity extends Activity {

	private CallBlockDatabaseAdapter databaseAdapter;
	private ListView lvContacts;
	private ArrayList<ContactObject> listContacts = new ArrayList<ContactObject>();
	private ContactsAdapter contactsAdapter;
	Resources rs;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		//LocalizationUtil.setupLanguage(getApplicationContext());
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pick_contact_phonebook);
		rs = getResources();
		initContactsList();
		Log.e("CONTACT TAB", "CONTACT TAB");
	}

	/*
	 * TyHH: init listview and set on item click listener for listview
	 */
	public void initContactsList() {
		databaseAdapter = new CallBlockDatabaseAdapter(getApplicationContext());
		lvContacts = (ListView) findViewById(R.id.list_contacts);
		contactsAdapter = new ContactsAdapter(getApplicationContext(),
				android.R.layout.simple_list_item_1, listContacts);
		dialog = new ProgressDialog(this);
		final AlertDialog.Builder alert = new AlertDialog.Builder(this);
		lvContacts.setOnItemClickListener(new ListView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				final ContactObject currentContact = listContacts.get(position);

				alert.setTitle(rs.getString(R.string.pick_alert_title));
				alert.setMessage(rs.getString(R.string.pick_alert_message));
				alert.setPositiveButton(rs.getString(R.string.ok),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								String phone = currentContact.getPhone().trim()
										.replace("-", "");
								// Toast.makeText(getApplicationContext(),
								// ""+phone, Toast.LENGTH_LONG).show();
								String nPhone="";
								if(phone.contains("+84")){
									nPhone = "0" + phone.substring(3);
								}else{
									nPhone = phone;
								}
								databaseAdapter.open();
								if (databaseAdapter.isPhoneExist(nPhone)) {
									databaseAdapter.close();
									Toast.makeText(
											getApplicationContext(),
											rs.getString(R.string.pc_phone_exist),
											Toast.LENGTH_LONG).show();
									dialog.cancel();
								} else {
									databaseAdapter.addBlackList(
											currentContact.getName(), nPhone,
											currentContact.getGroup(),
											currentContact.getType(), 0, 0, 0);
									databaseAdapter.close();
									getParent().setResult(Constants.RESPONSE_PICK_CONTACT_OK);
									finish();
								}

							}
						});
				alert.setNegativeButton(rs.getString(R.string.cancel),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								dialog.cancel();
							}
						});
				alert.show();
			}

		});
		new GetContactThread().execute();
		//loadContactsToList();
		//lvContacts.setAdapter(contactsAdapter);
	}

	
	
	private ProgressDialog dialog;
	
	public class GetContactThread extends
			AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			loadContactsToList();
			return null;
			// TODO Auto-generated method stub

		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			dialog.setMessage(rs.getString(R.string.pick_dialog_load));
			dialog.show();
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			// super.onPostExecute(result);
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			lvContacts.setAdapter(contactsAdapter);
		}
		
		private void loadContactsToList() {
			// TODO Auto-generated method stub
			if (listContacts != null)
				listContacts.clear();
			Cursor cr = getAllContacts();
			if (cr.moveToFirst()) {
				int indexOfColumnName = cr.getColumnIndex(Contacts.DISPLAY_NAME);
				int indexOfColumnID = cr.getColumnIndex(Contacts._ID);

				do {
					ContactObject contact = new ContactObject();
					contact.setName(cr.getString(indexOfColumnName));
					contact.setUri(cr.getString(indexOfColumnID));
					String id = cr.getString(indexOfColumnID);
					/* String name = cr.getString(indexOfColumnName); */
					Cursor crPhones = getPhoneByContactID(id);
					String phones = "";
					// String numberType = "";
					if (crPhones.moveToFirst()) {
						do {
							phones += crPhones.getString(crPhones
									.getColumnIndex(Phone.NUMBER)) + " ";
						} while (crPhones.moveToNext());
						// numberType =
						// crPhones.getString(crPhones.getColumnIndex(Phone.TYPE));
						if ("".equals(phones)) {
							phones = rs.getString(R.string.pick_string_nophone);
						}
						contact.setPhone(phones);
						// contact.setType(numberType);
					}
					crPhones.close();
					listContacts.add(contact);
				} while (cr.moveToNext());
			}
			cr.close();
		}

		/*
		 * TyHH: Get all contacts from provider
		 */
		public Cursor getAllContacts() {
			Uri uri = Contacts.CONTENT_URI;
			String[] projection = { Contacts._ID, Contacts.DISPLAY_NAME }; // get 2
																			// column
			String selection = null; // get all record
			String[] selectionArgs = null; // get
			String sortOrder = Contacts.DISPLAY_NAME + " ASC"; // order by ASC
			return getContentResolver().query(uri, projection, 
                    "HAS_PHONE_NUMBER = ?", new String[] { "1" }, 
                    sortOrder);
		}

		/*
		 * TyHH: Get a phone by ID
		 */
		public Cursor getPhoneByContactID(String _ID) {
			Uri uri = Phone.CONTENT_URI;
			String[] projection = null;
			String selection = Phone.CONTACT_ID + " = " + _ID;
			String[] selectionArgs = null;
			String sortOrder = null;
			return getContentResolver().query(uri, projection, selection,
					selectionArgs, sortOrder);
		}
	}

}
